package com.tmt.im.wallet.controler;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.im.wallet.controler.vo.ApplyRechargeRequest;
import com.tmt.im.wallet.service.RechargeHistoryService;
import com.tmt.springboot.common.restful.ExecuteResult;
import com.tmt.springboot.common.restful.IExecuteResult;
import com.tmt.springboot.common.restful.ResultWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ignite.Ignite;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * 充值控制器
 *
 * @Description TODO
 * @Author wuyi
 * @Date 2024/10/19 16:18
 * @Version 1.0
 **/
@Slf4j
@Async("asyncTaskExecutor")
@Tag(name = "充值相关接口", description = "充值相关接口")
@RestController
@RequestMapping("${api-url-prefix}/recharge")
public class RechargeController {

    private final Ignite ignite;

    private final RechargeHistoryService rechargeHistoryService;

    public RechargeController(Ignite ignite,
                              RechargeHistoryService rechargeHistoryService) {
        this.ignite = ignite;
        this.rechargeHistoryService = rechargeHistoryService;
    }

    @Operation(summary = "发起支付请求",
            description = "发起支付请求",
            operationId = "applyRecharge",
            parameters = {
                    @Parameter(name = "request", description = "申请充值请求对象")
            })
    @PostMapping(value = "/apply")
    public CompletableFuture<IExecuteResult<ResultWrapper<String>>> applyRecharge(@RequestBody @Validated ApplyRechargeRequest request,
                                                                                  Principal principal) {
        IExecuteResult<String> result = rechargeHistoryService.applyRecharge(request, principal);
        return CompletableFuture.completedFuture(ResultWrapper.from(result));
    }

    @Operation(summary = "支付结果同步回调接口",
            description = "支付结果同步回调接口",
            operationId = "syncConfirmRecharge",
            parameters = {
                    @Parameter(name = "request", description = "确认充值请求对象")
            })
    @GetMapping(value = "/confirm/sync")
    public CompletableFuture<Void> syncConfirmRecharge(HttpServletRequest request, HttpServletResponse response) {
        log.error("----{}----", "syncConfirmRecharge");
        for (String key : request.getParameterMap().keySet()) {
            log.error("1----{}={}----", key, request.getParameterMap().get(key)[0]);
        }
        rechargeHistoryService.syncConfirmRecharge(request, response);
        return CompletableFuture.completedFuture(null);
    }

    @Operation(summary = "支付结果异步回调接口",
            description = "支付结果异步回调接口",
            operationId = "asyncConfirmRecharge",
            parameters = {
                    @Parameter(name = "request", description = "确认充值请求对象")
            })
    @GetMapping(value = "/confirm/async")
    public CompletableFuture<Void> asyncConfirmRecharge(HttpServletRequest request,
                                                        HttpServletResponse response) {
        log.error("----{}----", "asyncConfirmRecharge");
        for (String key : request.getParameterMap().keySet()) {
            log.error("2----{}={}----", key, request.getParameterMap().get(key)[0]);
        }
        //接收充值回调的参数。
        Long rechargeHistoryId = rechargeHistoryService.asyncConfirmRecharge(request);
        if (rechargeHistoryId != null) {
            rechargeHistoryService.updateWalletBalance(rechargeHistoryId);
        }

        String actualPayAmount = request.getParameter("actualPayAmount");
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("price", actualPayAmount);
        jsonObject.put("time", sdf.format(new Date()));
        jsonObject.put("msg", "success");

        try (OutputStream out = response.getOutputStream()) {
            out.write(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
        } catch (Exception ex) {
        }
        return CompletableFuture.completedFuture(null);
    }

    @Operation(summary = "支付结果查询接口",
            description = "支付结果查询接口",
            operationId = "queryRechargeResult",
            parameters = {
                    @Parameter(name = "rechargeId", description = "要查询结果的充值记录ID")
            })
    @GetMapping(value = "/query")
    public CompletableFuture<IExecuteResult<ResultWrapper<Boolean>>> queryRechargeResult(@RequestParam("rechargeId") Long rechargeId, Principal principal) {
        StringBuilder error = new StringBuilder();
        if (rechargeHistoryService.queryRechargeResult(rechargeId, error)) {
            rechargeHistoryService.updateWalletBalance(rechargeId);
            return CompletableFuture.completedFuture(ResultWrapper.from(ExecuteResult.success(true)));
        }
        return CompletableFuture.completedFuture(ResultWrapper.from(ExecuteResult.failure(error.toString(), null)));
    }

}
